package com.sinoglobal.dumping.view;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Color;
import android.os.Handler;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.sinoglobal.dumping.R;
import com.squareup.picasso.Picasso;

/**
 * 自定义ListView(添加上下拉 head & footer)
 */
public class Dumpling_CustomListView extends ListView implements OnScrollListener {

    protected final static int RELEASE_To_REFRESH = 0;
    protected final static int PULL_To_REFRESH = 1;
    protected final static int REFRESHING = 2;
    protected final static int DONE = 3;
    protected final static int LOADING = 4;
    protected final static int DONE_TO_NULL = 5;

    private static final String TAG = "CustomListView";
    // 实际的padding的距离与界面上偏移距离的比例
    protected final static int RATIO = 3;

    protected LayoutInflater inflater;

    protected LinearLayout headView;

    protected TextView tipsTextview;
    protected ProgressBar progressBar;
    protected View head_bg_progress;

    // 用于保证startY的值在一个完整的touch事件中只被记录一次
    protected boolean isRecored;

    protected int headContentWidth;
    protected int headContentHeight;

    protected int startY;

    protected int state;

    protected boolean isBack;

    protected OnRefreshListener refreshListener;

    protected boolean isRefreshable;
    protected boolean isRefreshableShow;
    protected View footer;
    protected TextView mMore;
    protected RelativeLayout mMoreBg;
    protected Dumpling_ImageProgressBar mProgress;

    protected LoadData loadData;

    // show header
    private boolean isNeedHeader = true;
    // show footer
    // show header loading tip
    private boolean isShowLoadingTip = true;

    private String pullTipLabel;

//	private ClockAnimView clockView;

    private Context context;


    public Dumpling_CustomListView(Context context) {
        super(context);
        init(context);
        this.context = context;
    }

    public Dumpling_CustomListView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }

    public Dumpling_CustomListView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(context, attrs);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    protected void init(Context context) {
        init(context, null);
    }

    protected void init(Context context, AttributeSet attrs) {
//		if (attrs != null) {
//			TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.Dumpling_CustomListView);
//			this.isNeedHeader = a.getBoolean(R.styleable.Dumpling_CustomListView_isNeedHeader, true);
//			this.isNeedFooter = a.getBoolean(R.styleable.Dumpling_CustomListView_isNeedFooter, false);
//			this.noMoreTip = a.getString(R.styleable.Dumpling_CustomListView_noMoreText);
//			a.recycle();
//		}
        // setCacheColorHint(context.getResources().getColor(R.color.transparent));
        inflater = LayoutInflater.from(getContext());

//		if (isNeedHeader) {
        initHeaderView();
        measureView(headView);
        headContentHeight = headView.getMeasuredHeight();
        headContentWidth = headView.getMeasuredWidth();

        headView.setPadding(0, -1 * headContentHeight, 0, 0);
        headView.invalidate();
        addHeaderView(headView, null, false);
//		}
        initFooterView();

//		if (isNeedFooter) {
//		}

//		if (isNeedHeader || isNeedFooter) {
        setOnScrollListener(this);
//		}

        state = DONE;
        isRefreshable = false;
    }

    private void initHeaderView() {
        headView = (LinearLayout) inflater.inflate(R.layout.dumpling_costomlistview_header, null);
        progressBar = (ProgressBar) headView.findViewById(R.id.head_progressBar);
        tipsTextview = (TextView) headView.findViewById(R.id.head_tipsTextView);
        head_bg_progress = headView.findViewById(R.id.head_bg_progress);
//		clockView = (ClockAnimView) headView.findViewById(R.id.head_clock);
    }

    private void initFooterView() {
        footer = inflater.inflate(R.layout.dumpling_customlistview_footer, null);
        mMore = (TextView) footer.findViewById(R.id.footer_more);
//		mMore.setText(noMoreTip);
        mProgress = (Dumpling_ImageProgressBar) footer.findViewById(R.id.footer_progress);
        footer.setVisibility(View.GONE);
        addFooterView(footer);
    }


    public boolean onTouchEvent(MotionEvent event) {
        isRefreshableShow = true;
        if (!isNeedHeader) {
            return super.onTouchEvent(event);
        }
        if (isRefreshable) {
            // Log.d("ontouch","action = " + event.getAction() + " isRecored = "
            // + isRecored + " state = " + state);
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    if (getFirstVisiblePosition() == 0 && !isRecored) {
                        isRecored = true;
                        startY = (int) event.getY();
                    }
                    break;
                case MotionEvent.ACTION_MOVE:
                    int tempY = (int) event.getY();
                    if (!isRecored && getFirstVisiblePosition() == 0) {
                        isRecored = true;
                        startY = tempY;
                    }
                    if (state != REFRESHING && isRecored && state != LOADING) {
                        // 保证在设置padding的过程中，当前的位置一直是在head，否则如果当列表超出屏幕的话，当在上推的时候，列表会同时进行滚动
                        // 可以松手去刷新了
                        if (state == RELEASE_To_REFRESH) {
                            setSelection(0);
                            // 往上推了，推到了屏幕足够掩盖head的程度，但是还没有推到全部掩盖的地步
                            if (((tempY - startY) / RATIO < headContentHeight) && (tempY - startY) > 0) {
                                state = PULL_To_REFRESH;
                                changeHeaderViewByState();
                            }
                            // 一下子推到顶了
                            else if (tempY - startY <= 0) {
                                state = DONE;
                                changeHeaderViewByState();
                            }
                            // 往下拉了，或者还没有上推到屏幕顶部掩盖head的地步
                            else {
                                // 不用进行特别的操作，只用更新paddingTop的值就行了
                            }
                        }
                        // 还没有到达显示松开刷新的时候,DONE或者是PULL_To_REFRESH状态
                        if (state == PULL_To_REFRESH) {
                            setSelection(0);
                            // 下拉到可以进入RELEASE_TO_REFRESH的状态
                            if ((tempY - startY) / RATIO >= headContentHeight) {
                                state = RELEASE_To_REFRESH;
                                isBack = true;
                                changeHeaderViewByState();
                            }
                            // 上推到顶了
                            else if (tempY - startY <= 0) {
                                state = DONE;
                                changeHeaderViewByState();
                            }
                        }
                        // done状态下
                        if (state == DONE) {
                            if (tempY - startY > 0) {
                                state = PULL_To_REFRESH;
                                changeHeaderViewByState();
                            }
                        }
                        // 更新headView的size
                        if (state == PULL_To_REFRESH) {
                            int top = -1 * headContentHeight + (tempY - startY) / RATIO;
                            headView.setPadding(0, top, 0, 10);
//						clockView.updateNeedlePosition((float) top / headView.getMeasuredHeight());

                        }
                        // 更新headView的paddingTop
                        if (state == RELEASE_To_REFRESH) {
                            int top = (tempY - startY) / RATIO - headContentHeight;
                            headView.setPadding(0, top, 0, 10);
                        }
                    }
                    break;
                case MotionEvent.ACTION_UP:
                    if (state != REFRESHING && state != LOADING) {
                        if (state == DONE) {
                            // 什么都不做
                        }
                        if (state == PULL_To_REFRESH) {
                            state = DONE;
                            changeHeaderViewByState();
                        }
                        if (state == RELEASE_To_REFRESH) {
                            state = REFRESHING;
                            changeHeaderViewByState();
                            onRefresh();
                        }
                    }
                    isRecored = false;
                    isBack = false;
                    break;
            }
        }
        return super.onTouchEvent(event);
    }

    // 当状态改变时候，调用该方法，以更新界面
    protected void changeHeaderViewByState() {
        switch (state) {
            case RELEASE_To_REFRESH:
                updateLoadingTip(TextUtils.isEmpty(pullTipLabel) ? "去找找新的数据哈~" : pullTipLabel);
                break;
            case PULL_To_REFRESH:
                updateLoadingTip(TextUtils.isEmpty(pullTipLabel) ? "去找找新的数据哈~" : pullTipLabel);
                break;

            case REFRESHING:
                headView.setPadding(0, 15, 0, 15);
//			clockView.startAnim();
                updateLoadingTip(TextUtils.isEmpty(pullTipLabel) ? "去找找新的数据哈~" : pullTipLabel);
                break;
            case DONE:
                if (headView != null) {
//				FanXQApplication.getHandler().postDelayed(new Runnable() {
//					@Override
//					public void run() {
                    headView.setPadding(0, -1 * headContentHeight, 0, 0);
//						clockView.stopAnim();
                    // tipsTextview.setVisibility(View.GONE);
//					}
//				}, 0);
                }
                break;
            case DONE_TO_NULL:
                headView.setPadding(0, 15, 0, 15);
                updateLoadingTip(TextUtils.isEmpty(pullTipLabel) ? "去找找新的数据哈~" : pullTipLabel);
                break;
        }
        isRefreshableShow = false;
    }

    private void updateLoadingTip(String tip) {
        if (isShowLoadingTip) {
            tipsTextview.setText(tip);
            tipsTextview.setVisibility(View.VISIBLE);
        }
    }

    /**
     * has 0没有,1还有更多
     */
    public void setHas(int has) {
        if (mMore == null) {
            return;
        }
        switch (has) {
            case 0:
                mMore.setText("没有更多数据了");
                mProgress.setVisibility(View.GONE);
                // mMore.setVisibility(8);
                break;
            default:
                // mMore.setVisibility(0);
                mMore.setText("加载中");
                mProgress.setVisibility(View.VISIBLE);
                mMore.setVisibility(View.VISIBLE);
                break;
        }
    }


    public void setOnRefreshListener(OnRefreshListener refreshListener) {
        this.refreshListener = refreshListener;
        isRefreshable = true;
    }

    public interface OnRefreshListener {
        void onRefresh(Dumpling_CustomListView listView);
    }

    public void onRefreshComplete() {
        refreshComplete();
        if (mMore != null) {
            mMore.setText("没有更多");
        }
    }

    protected void refreshComplete() {
        state = DONE;
        updateRefreshTime();
        changeHeaderViewByState();
        if (mProgress != null) {
            mProgress.setVisibility(View.GONE);
        }
    }

    protected void onRefresh() {
        if (refreshListener != null) {
            refreshListener.onRefresh(this);
        }
    }

    // 此处是“估计”headView的width以及height
    protected void measureView(View child) {
        ViewGroup.LayoutParams p = child.getLayoutParams();
        if (p == null) {
            p = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        }
        int childWidthSpec = ViewGroup.getChildMeasureSpec(0, 0 + 0, p.width);
        int lpHeight = p.height;
        int childHeightSpec;
        if (lpHeight > 0) {
            childHeightSpec = MeasureSpec.makeMeasureSpec(lpHeight, MeasureSpec.EXACTLY);
        } else {
            childHeightSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
        }
        child.measure(childWidthSpec, childHeightSpec);
    }

    public void setAdapter(BaseAdapter adapter) {
        updateRefreshTime();
        super.setAdapter(adapter);
    }

    protected void updateRefreshTime() {
        // SimpleDateFormat format = new
        // SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // String date = format.format(new Date());
        // lastUpdatedTextView.setText("最近更新: " + date);
    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {

        final Picasso picasso = Picasso.with(getContext());
        if (scrollState == SCROLL_STATE_IDLE || scrollState == SCROLL_STATE_TOUCH_SCROLL) {
            picasso.resumeTag(context);
        } else {
            picasso.pauseTag(context);
        }
        if (state != PULL_To_REFRESH && view.getLastVisiblePosition() == view.getCount() - 1 && scrollState == OnScrollListener.SCROLL_STATE_IDLE) {
            if (loadData != null && loadData.isHasMore()) {
                footerIsLoading();
                mHandler.postAtTime(new Runnable() {

                    @Override
                    public void run() {
                        loadData.automLoadData();
                    }
                }, 2000);
            } else {

//				Toast.makeText(context, "没有更多数据", Toast.LENGTH_SHORT).show();;
//				if (isClickFooterTextView) {
//					footerIsEnd();
//				}
            }
        }

    }

    private Handler mHandler = new Handler();
    public void getMore(LoadData loadData) {
        this.loadData = loadData;
    }

    public interface LoadData {
        void automLoadData();

        boolean isHasMore();
    }

    /**
     * 显示或隐藏footer
     *
     * @param showFooterFlag
     */
    public void showFooter2(boolean showFooterFlag) {
        if (footer != null) {
            if (showFooterFlag) {
                footer.setVisibility(View.VISIBLE);
            } else {
                footer.setVisibility(View.GONE);
            }
        }
    }

    /**
     * footer是否loading状态
     */
    public void footerIsLoading() {
        if (footer != null) {
            if (isRefreshableShow) {
                footer.setVisibility(View.VISIBLE);
                mProgress.setVisibility(View.VISIBLE);
                mMore.setText("加载中");
//				mMore.setTextColor(getResources().getColor(R.color.white));
            }
        }
    }

    /**
     * 对addHeaderView进行try...catch,防止在4.1以下版本出现java.lang.IllegalStateException:
     * Cannot add header view to list -- setAdapter has already been called
     */
    @Override
    public void addHeaderView(View v) {
        try {
            super.addHeaderView(v);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
